<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class Admin extends Authenticatable
{
    use HasApiTokens, Notifiable;

    protected $fillable = [
        'username',
        'email',
        'password',
        'name',
        'phone',
        'avatar',
        'status',
        'last_login_at',
        'last_login_ip'
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'last_login_at' => 'datetime',
    ];

    /**
     * 角色关系
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'admin_role');
    }

    /**
     * 判断是否有某个角色
     */
    public function hasRole($role)
    {
        if (is_string($role)) {
            return $this->roles->contains('slug', $role);
        }

        return !!$role->intersect($this->roles)->count();
    }

    /**
     * 判断是否有某个权限
     */
    public function hasPermission($permission)
    {
        // 超级管理员拥有所有权限
        if ($this->hasRole('super_admin')) {
            return true;
        }

        // 检查所有角色是否拥有该权限
        return $this->roles->flatMap->permissions->contains('slug', $permission);
    }
}
